#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = 'gtlions'
import os
import sys
import smtplib
import mimetypes
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart


# 红色标记的修改成自己的信息
SMTP_SERVER = 'smtp.139.com'
EMAIL_USER = 'gtlions.l'
EMAIL_PASSWD = 'password'
EMAIL_SUBJECT = 'This is a test email'
FROM_USER = 'gtlions.l@139.com'
TO_USERS = ['gtlions@139.com']


def mysendmail(fromaddr, toaddrs, subject, attfile):
    COMMASPACE = ','
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = COMMASPACE.join(toaddrs)
    msg['Subject'] = subject

    # 邮件内容
    txt = MIMEText("this is the contents of the email!")
    msg.attach(txt)

    # 添加附件
    fileName = attfile
    # fileName = r'/Users/gtlions/Downloads/psycopg2-2.5.3.tar.gz'
    ctype, encoding = mimetypes.guess_type(fileName)
    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    att = MIMEImage((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], _subtype=subtype)
    att.add_header('Content-Disposition', 'attachment', filename=fileName)
    msg.attach(att)

    # #添加附件, 如果有多个附件，就多添加几个
    #
    # fileName = r'/home/oracle/awr.html'
    #
    # ctype, encoding = mimetypes.guess_type(fileName)
    #
    # if ctype is None or encoding is not None:
    #     ctype = 'application/octet-stream'
    #
    # maintype, subtype = ctype.split('/', 1)
    #
    # att = MIMEImage((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], _subtype=subtype)
    #
    # att.add_header('Content-Disposition', 'attachment', filename=fileName)
    #
    # msg.attach(att)

    server = smtplib.SMTP(SMTP_SERVER)
    server.login(EMAIL_USER, EMAIL_PASSWD)
    server.sendmail(fromaddr, toaddrs, msg.as_string())
    server.quit()


if __name__ == '__main__':
    if sys.argv[1]:
        attfile = sys.argv[1]
    mysendmail(FROM_USER, TO_USERS, EMAIL_SUBJECT, attfile)
    print 'send successful'
